<template>
    <div class="white-box">
        <title-more title="交易分析">
            <template #sub>
                <el-popover placement="right-start" title="" :width="300" trigger="hover">
                    <template #reference>
                        <el-icon color="#C1C1C1" :size="18"><QuestionFilled /></el-icon>
                    </template>
                    <template #default>
                        <p class="p-popover">默认筛选当天</p>
                        <p class="p-popover">筛选选定日期范围</p>
                    </template>
                </el-popover>
            </template>
        </title-more>
        <div class="task-one" style="margin-bottom: 32px">
            <div class="task-one__item">
                <span class="task-one__label">日期范围：</span>
                <el-date-picker
                    v-model="area_time"
                    type="daterange"
                    unlink-panels
                    value-format="YYYY-MM-DD"
                    range-separator="至"
                    start-placeholder="开始日期"
                    end-placeholder="结束日期"
                />
            </div>
            <div class="task-one__btn">
                <el-button type="primary" :loading="search_btn" :icon="Search" @click="handleSearch">查询</el-button>
            </div>
        </div>
        <div class="chart-one">
            <div class="chart-one__left">
                <div class="chart-one__item">
                    <div class="chart-data__item">
                        <div class="chart-data__text">访客数</div>
                        <p class="chart-data__nums">{{ objs.visitors || 0 }}</p>
                    </div>
                </div>
                <div class="chart-one__item">
                    <div class="chart-data__item">
                        <div class="chart-data__text">下单人数</div>
                        <p class="chart-data__nums">{{ objs.order_user || 0 }}</p>
                    </div>
                    <div class="chart-data__item">
                        <div class="chart-data__text">下单金额(元)</div>
                        <p class="chart-data__nums">{{ objs.order_price || "0.00" }}</p>
                    </div>
                </div>
                <div class="chart-one__item">
                    <div class="chart-data__item">
                        <div class="chart-data__text">支付人数</div>
                        <p class="chart-data__nums">{{ objs.pay_user || 0 }}</p>
                    </div>
                    <div class="chart-data__item">
                        <div class="chart-data__text">支付金额(元)</div>
                        <p class="chart-data__nums">{{ objs.pay_price || "0.00" }}</p>
                    </div>
                    <div class="chart-data__item">
                        <div class="chart-data__text">客单价(元)</div>
                        <p class="chart-data__nums">{{ objs.pay_unit_price || "0.00" }}</p>
                    </div>
                </div>
            </div>
            <div class="chart-one__right">
                <div class="chart-one__per chart-per__one">
                    <p>访问-下单转化率</p>
                    <p>{{ objs.order_conversion }}%</p>
                </div>
                <div class="chart-one__per chart-per__two">
                    <p>下单-支付转化率</p>
                    <p>{{ objs.pay_conversion }}%</p>
                </div>
                <div class="chart-one__per chart-per__three">
                    <p>访问-支付转化率</p>
                    <p>{{ objs.visitor_conversion }}%</p>
                </div>
            </div>
        </div>
    </div>
    <div class="white-box">
        <title-more title="交易构成">
            <template #sub>
                <el-popover placement="right-start" title="" :width="300" trigger="hover">
                    <template #reference>
                        <el-icon color="#C1C1C1" :size="18"><QuestionFilled /></el-icon>
                    </template>
                    <template #default>
                        <p class="p-popover">默认筛选当天</p>
                        <p class="p-popover">按选定日期往前推一个月</p>
                    </template>
                </el-popover>
            </template>
            <template #right>
                <div>
                    <el-date-picker
                        v-model="day_gc"
                        type="date"
                        value-format="YYYY-MM-DD"
                        :disabled-date="disabledDate"
                        placeholder="请选择时间"
                        @change="changeDayGc"
                    />
                </div>
            </template>
        </title-more>
        <div class="echars-one__cont">
            <div id="echart-pay" class="echart-view"></div>
        </div>
        <div class="echars-table">
            <el-table
                class="table-mb"
                :data="chartOneArrs"
                :header-cell-style="{ background: '#F5F7FA' }"
                element-loading-background="rgba(255, 255, 255, 0.6)"
            >
                <el-table-column prop="name" label="成交类型"></el-table-column>
                <el-table-column prop="value" label="支付金额（元）"></el-table-column>
                <el-table-column label="环比上月">
                    <template #default="{ row }">
                        <div class="table-ratio" :style="{ color: row.ring_ratio > 0 ? '#f3262a' : '#6DAF45' }">
                            <el-icon color="#f3262a" size="16px" v-if="row.ring_ratio > 0"><Top /></el-icon>
                            <el-icon color="#6DAF45" size="16px" v-else><Bottom /></el-icon>{{ row.ring_ratio }}%
                        </div>
                    </template>
                </el-table-column>
                <el-table-column prop="pay_user" label="支付人数"></el-table-column>
                <el-table-column label="环比上月">
                    <template #default="{ row }">
                        <div class="table-ratio" :style="{ color: row.ring_ratio_user > 0 ? '#f3262a' : '#6DAF45' }">
                            <el-icon color="#f3262a" size="16px" v-if="row.ring_ratio_user > 0"><Top /></el-icon>
                            <el-icon color="#6DAF45" size="16px" v-else><Bottom /></el-icon>{{ row.ring_ratio_user }}%
                        </div>
                    </template>
                </el-table-column>
            </el-table>
        </div>
    </div>
    <div class="white-box">
        <title-more title="地域分析">
            <template #right>
                <div>
                    <el-date-picker v-model="months" type="month" value-format="YYYY-MM" placeholder="请选择月份" @change="changeMonth" />
                </div>
            </template>
        </title-more>
        <div id="echart-china" class="map-box" ref="myMap"></div>
        <div class="echars-table">
            <el-table
                class="table-mb"
                :data="arr_data"
                :header-cell-style="{ background: '#F5F7FA' }"
                element-loading-background="rgba(255, 255, 255, 0.6)"
                v-loading="loading"
            >
                <el-table-column label="TOP排名" type="index" :index="indexMethod" width="120" />
                <el-table-column prop="city" label="城市"></el-table-column>
                <el-table-column prop="total_amount" label="支付金额（元）"></el-table-column>
                <el-table-column prop="pay_user_count" label="支付人数"></el-table-column>
            </el-table>
            <el-pagination
                background
                v-model:current-page="page"
                v-model:page-size="pageSize"
                :page-sizes="pageSizeNum"
                :total="totalNums"
                layout="total, sizes, prev, pager, next, jumper"
            >
            </el-pagination>
        </div>
    </div>
    <go-back />
</template>

<script setup>
import { getCurrentInstance, ref, onMounted, onBeforeUnmount, watch } from "vue"
import { Search, QuestionFilled, Top, Bottom } from "@element-plus/icons-vue"
import TitleMore from "@components/title-more.vue"
import GoBack from "@components/GoBack.vue"
import OneLoad from "@mixins/one-load"

// echarts
import EchartsChina from "@common/echarts-china"
import EchartsPie from "@common/echarts-pie"

const { proxy } = getCurrentInstance()

onMounted(() => {
    getDataInfo()
    getChinaMaps()
    window.onresize = echartResize
})

onBeforeUnmount(() => {
    echartsDispose()
    window.onresize = null
    chart_area = null
})

// 概况
const objs = ref({
    visitors: 0, // 访客数
    order_user: 0, // 下单人数
    order_price: "0.00", // 下单金额
    pay_user: 0, // 支付人数
    pay_price: "0.00", // 支付金额
    pay_unit_price: "0.00", // 客单价
    order_conversion: "0.00", // 访问-下单转化率
    pay_conversion: "0.00", // 下单-支付转化率
    visitor_conversion: "0.00", // 访问-下单转化率
})
const allObjs = ref({})
function getDataInfo(status = true) {
    let days = proxy.$util.getDate()
    proxy.$axios
        .get("data/order/tongji", {
            params: {
                s_day: area_time.value ? area_time.value[0] : days, // 交易分析
                l_day: area_time.value ? area_time.value[1] : days,
            },
        })
        .then((res) => {
            search_btn.value = false
            if (res.data.code == 0) {
                let result = res.data.data
                objs.value.visitors = result.uv_count
                objs.value.order_user = result.order_total_count
                objs.value.order_price = result.order_total_amount
                objs.value.pay_user = result.order_pay_count
                objs.value.pay_price = result.order_pay_amount
                objs.value.pay_unit_price = result.order_pay_count == 0 ? 0 : (result.order_pay_amount / result.order_pay_count).toFixed(2)
                objs.value.order_conversion = result.uv_count == 0 ? 0 : ((result.order_total_count / result.uv_count) * 100).toFixed(2)
                objs.value.pay_conversion = result.order_total_count == 0 ? 0 : ((result.order_pay_count / result.order_total_count) * 100).toFixed(2)
                objs.value.visitor_conversion = result.uv_count == 0 ? 0 : ((result.order_pay_count / result.uv_count) * 100).toFixed(2)
                allObjs.value = result
                status && getOneArrs()
                status && getTwoArrs()
            } else {
                proxy.$message({ message: res.data.msg, type: "error" })
            }
        })
        .catch((err) => {
            search_btn.value = false
        })
}

// 筛选
const area_time = ref("")
const search_btn = ref(false)
const handleSearch = () => {
    if (!area_time.value) {
        proxy.$message({ message: "请选择开始和结束日期", type: "warning" })
        return
    }
    search_btn.value = true
    getDataInfo(false)
}

/**
 * 图表
 * @param {Object} chart_pay 交易构成
 * @param {Object} chart_area 地区分析
 */
let chart_pay = null
let chart_area = null
function echartResize() {
    chart_pay.resize()
}
function echartsDispose() {
    chart_pay != null && chart_pay.dispose()
    chart_pay = null
}

// 交易构成
const chartOneArrs = ref([])
const day_gc = ref("")
// 筛选日期
const changeDayGc = (val) => {
    day_gc.value = val
    chartOneArrs.value = []
    echartsDispose()
    getOneArrs()
}
function getOneArrs() {
    proxy.$axios
        .get("data/order/tongjiInfo", {
            params: {
                day: day_gc.value,
            },
        })
        .then((res) => {
            if (res.data.code == 0) {
                let result = res.data.data
                // 环比上月新客户支付增长率
                let news_month =
                    result.new_last_amount == 0
                        ? (result.new_pay_amount - result.new_last_amount).toFixed(2)
                        : (((result.new_pay_amount - result.new_last_amount) / result.new_last_amount) * 100).toFixed(2)

                // 环比上月新客户成交增长率
                let news_users =
                    result.new_last_count == 0
                        ? ((result.new_pay_count - result.new_last_count) * 100).toFixed(2)
                        : (((result.new_pay_count - result.new_last_count) / result.new_last_count) * 100).toFixed(2)

                // 环比上月老客户支付增长率
                let old_month =
                    result.old_last_amount == 0
                        ? (result.old_pay_amount - result.old_last_amount).toFixed(2)
                        : (((result.old_pay_amount - result.old_last_amount) / result.old_last_amount) * 100).toFixed(2)

                // 环比上月老客户成交增长率
                let old_users =
                    result.old_last_count == 0
                        ? ((result.old_pay_count - result.old_last_count) * 100).toFixed(2)
                        : (((result.old_pay_count - result.old_last_count) / result.old_last_count) * 100).toFixed(2)

                chartOneArrs.value = [
                    { value: result.old_pay_amount, ring_ratio: old_month, pay_user: result.old_pay_count, ring_ratio_user: old_users, name: "老客户成交" },
                    { value: result.new_pay_amount, ring_ratio: news_month, pay_user: result.new_pay_count, ring_ratio_user: news_users, name: "新客户成交" },
                ]
                chartPayInfo()
            } else {
                proxy.$message({ message: res.data.msg, type: "error" })
            }
        })
        .catch((err) => {})
}
function chartPayInfo() {
    chart_pay = proxy.$echarts.init(document.getElementById("echart-pay"))
    let series = [
        {
            name: "交易构成",
            type: "pie",
            radius: ["30%", "70%"],
            avoidLabelOverlap: false,
            label: {
                show: false,
                position: "center",
            },
            labelLine: {
                show: false,
            },
            data: chartOneArrs.value,
        },
    ]

    let legend = {
        left: "center",
    }
    let option = EchartsPie(series, "{b}<br />支付金额：{c}<br />占比: {d}%", legend)
    chart_pay.setOption(option)
}

// 中国地图
let dates = proxy.$util.getDate().substring(0, 7)
const months = ref(dates)
const prodArrs = ref([]) // 统计省份
// 筛选月份
const changeMonth = (val) => {
    months.value = val
    prodArrs.value = []
    getTwoArrs()
}
function getTwoArrs() {
    let data = {}
    months.value && (data.month = months.value)
    proxy.$axios
        .get("data/order/province", {
            params: data,
        })
        .then((res) => {
            if (res.data.code == 0) {
                let result = res.data.data
                result.map((item) => {
                    item.name = item.province
                    item.value = item.total_amount
                })
                prodArrs.value = result
                pubRefreshParams(getList)
                chartChinaMap()
            } else {
                proxy.$message({ message: res.data.msg, type: "error" })
            }
        })
        .catch((err) => {})
}
function chartChinaMap() {
    chart_area == null && (chart_area = proxy.$echarts.init(document.getElementById("echart-china")))
    // 是中国就“china”，省份则是字母全拼，比如“yunnan”，chinaMap——geoJSON数据
    proxy.$echarts.registerMap("china", chinaMap.value)
    let series = [
        {
            name: "付款金额",
            type: "map",
            mapType: "china",
            emphasis: {
                label: {
                    show: false, // 城市模式下，鼠标移上去不显示省份名称
                },
            },
            data: prodArrs.value,
        },
    ]
    let option = EchartsChina("付款金额地域分布", series)
    chart_area.setOption(option)
}

/**
 * minxin列表加载-城市排行
 */
const { page, pageSizeNum, pageSize, loading, arr_data, totalNums, pubParams, pubRefreshParams, getdata } = OneLoad()

// 切换每页显示条数
watch(pageSize, (val) => {
    page.value = 1
    pubParams(getList)
})
// 跳转第几页
watch(page, (val) => {
    pubParams(getList)
})

const indexMethod = (index) => {
    return index + 1 + (page.value - 1) * pageSize.value
}
function getList() {
    let params = {
        page: page.value,
        limit: pageSize.value,
    }
    months.value && (params.month = months.value)
    getdata("data/order/city", params)
}

const chinaMap = ref("")
function getChinaMaps() {
    proxy.$axios
        .get("china_al.json")
        .then((res) => {
            chinaMap.value = res.data
        })
        .catch((err) => {})
}

const disabledDate = (time) => {
    return time.getTime() > Date.now()
}
</script>
<script>
export default {
    name: "TradingAnalytics",
}
</script>

<style lang="less" scoped>
.p-popover {
    font-size: @font-size-md;
    color: #595961;
    margin: @margin-xs 0px;
}
.table-ratio {
    display: flex;
    align-items: center;
    :deep(.el-icon) {
        font-weight: bold;
    }
}
.chart-one {
    display: flex;
    .chart-one__left {
        flex: 1;
        margin-right: -50px;
        .chart-one__item {
            display: flex;
            margin-bottom: 2px;
            height: 80px;
            padding: 20px 30px;
            box-sizing: border-box;
            .chart-data__item {
                margin-right: 40px;
                .chart-data__text {
                    color: @gray-7;
                    margin-bottom: 10px;
                }
                .chart-data__nums {
                    font-size: 16px;
                    color: @gray-8;
                    font-weight: bold;
                }
            }
            &:first-child {
                background-color: #edf4ff;
            }
            &:nth-of-type(2) {
                background-color: #f0faf2;
            }
            &:last-child {
                background-color: #fff7e8;
            }
        }
    }
    .chart-one__right {
        flex: none;
        // background: url("../../assets/images/conversion-bg.png") no-repeat;
        background: url("https://cdn.huashushop.com/tenant_593be52a46f869eea8b31d146d21de7a/album/202304/20230413_864426055ffd83f2fec62f82469810b0.png")
            no-repeat;
        background-size: cover;
        width: 350px;
        height: 245px;
        position: relative;
        .chart-one__per {
            position: absolute;
            color: @gray-7;
            p {
                &:first-child {
                    margin-bottom: 4px;
                }
            }
        }
        .chart-per__one {
            right: 64px;
            top: 48px;
        }
        .chart-per__two {
            top: 132px;
            right: 64px;
        }
        .chart-per__three {
            bottom: 0;
            right: 85px;
        }
    }
}
.echart-view {
    width: 100%;
    height: 340px;
}
.map-box {
    margin: 0 auto;
    width: 640px;
    height: 480px;
}
</style>
